﻿/* $RCSFile: RadTreeComboModules.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/ADNCRM.Core/UI/WebControls/RadTreeComboModules.cs $
 * $log$
 * Revision 6 2010/08/06 19:56:30  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Reflection;
using System.Collections;
using System.Data;
using System.Web;
using System.Text;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Globalization;

using AddonNice.Core;
using AddonNice.UI;
using AddonNice.UI.WebControls;
using AddonNice.UI.DataTypes;
using AddonNice.Configuration;
using AddonNice.Diagnostics;
using AddonNice.Helpers;
using AddonNice.Settings;
using AddonNice.Security;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.UI.WebControls
{
	[ToolboxData("<{0}:RadTreeComboModules runat='server'></{0}:RadTreeComboModules>")]
    public class RadTreeComboModules : RadTreeComboPages
    {
        protected class ModuleComboTemplate : RadTreeComboPages.PageComboTemplate
        {
            ModulesDB ModDB             =   new ModulesDB();

            public ModuleComboTemplate(int pID,string wskin): base(pID,wskin)
            {
                if (WebControlsTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadTreeComboModules ModuleComboTemplate Ctor PortalID: {0}, Skin: {1}", pID, wskin), WebControlsTraceSwitch.Sw.Info);
            }

            protected override void InstallDataBinder()
            {
                RadTree1.DataBinding += new EventHandler(RadTree1_DataBindingModules);
            }

            void RadTree1_DataBindingModules(object sender, EventArgs e)
            {
                if (WebControlsTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadTreeComboModules PageComboTemplate RadTree1_DataBinding BEG sender: {0}", sender), WebControlsTraceSwitch.Sw.Info);
                RadTreeView RadTree1                    =  (RadTreeView)sender;

                bool SelectFirst                        =   ((RadTreeComboPages)ComboItem.ComboBoxParent).SelectFirst && string.IsNullOrEmpty(selVal);
                bool SelectSel                          =   !string.IsNullOrEmpty(selVal);
		        // Populate the "Add Module" Data
                SqlDataReader drCurrentModuleDefinitions =  null;
                try
                {
                    drCurrentModuleDefinitions          =   ModDB.GetCurrentModuleDefinitions(PortalID);
                    string CRMAdmin                     =   Config.CRMAdminRole;
                    string DbAdmin                      =   Config.InternalAdminRole;

			        bool isAdmin			            =   PortalSecurity.IsUserInRoles(CRMAdmin);
                    bool IncludeAdmin                   =   ((RadTreeComboModules)ComboItem.ComboBoxParent).IncludeAdmin;
                    string nmCat                        =   LocalizeHelper.Localize("ADMIN_MOD_CAT",DbAdmin);

                    RadTreeNode ndAdmin                 =   new RadTreeNode(nmCat,"0");
                    if ( IncludeAdmin )
                        RadTree1.Nodes.Add(ndAdmin);
                    nmCat                               =   LocalizeHelper.Localize("NORMAL_MOD_CAT",StStr.NormalModuleCat);
                    RadTreeNode ndNormal                =   new RadTreeNode(nmCat,"1");
                    ndNormal.Expanded                   =   true;
                    RadTree1.Nodes.Add(ndNormal);

                    // only users member of the CRMAdmin role can add Admin modules
                    while (drCurrentModuleDefinitions.Read())
                    {
                        bool adminModule                =   bool.Parse(drCurrentModuleDefinitions[StStr.DBAdmin].ToString());
                        string Category                 =   (string)drCurrentModuleDefinitions[StStr.DBCategory];
                        if ( isAdmin || !adminModule )
                        {
                            if ( !IncludeAdmin && adminModule )
                                continue;
                           RadTreeNode nd               =   new RadTreeNode((string)drCurrentModuleDefinitions[StStr.DBFriendlyName],
                                                            drCurrentModuleDefinitions[StStr.DBModuleDefID].ToString());
                            if ( ( SelectSel && nd.Value == selVal ) || SelectFirst )
                            {
                                SelectFirst             =   false;
                                nd.Selected             =   true;
                                if (WebControlsTraceSwitch.Sw.TraceVerbose)
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadTreeComboModules ModuleComboTemplate RadTree1_DataBinding selected nd.Text: {0}, ComboItem != null: {1}", nd.Text,ComboItem != null ), WebControlsTraceSwitch.Sw.Info);
                                if (WebControlsTraceSwitch.Sw.TraceVerbose)
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadTreeComboModules ModuleComboTemplate RadTree1_DataBinding Combo Ok nd.Text: {0}.", nd.Text ), WebControlsTraceSwitch.Sw.Info);
                                ComboItem.Text          =   nd.Text;
                                ComboItem.Value         =   nd.Value;
                                ComboItem.Selected      =   true;
                            }
                            if ( adminModule )
                                    ndAdmin.Nodes.Add(nd);
                            else if (Category.ToLower() == "normal")
                                ndNormal.Nodes.Add(nd);
                            else
                            {
                                RadTreeNode ndNewCat    =   RadTree1.Nodes.FindNodeByText(Category,true);
                                if (ndNewCat == null)
                                {
                                    ndNewCat            =   new RadTreeNode(Category, "2");
                                    ndNewCat.Expanded   =   true;
                                    RadTree1.Nodes.Add(ndNewCat);
                                }
                                ndNewCat.Nodes.Add(nd);
                            }
                        }
                    }
                    // Should we skip any Module
                    if (WebControlsTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadTreeComboModules ModuleComboTemplate RadTree1_DataBinding SkipPageList: [{0}]", ((RadTreeComboModules)ComboItem.ComboBoxParent).SkipList.ToString()), WebControlsTraceSwitch.Sw.Info);
                    if (!string.IsNullOrEmpty(((RadTreeComboModules)ComboItem.ComboBoxParent).SkipList))
                    {
                        string[] moduleID     =   ((RadTreeComboModules)ComboItem.ComboBoxParent).SkipList.Split(new char[]{';'},StringSplitOptions.RemoveEmptyEntries);
                        for (int i=0; i < moduleID.Length ; i++ )
                        {
                            if ( string.IsNullOrEmpty(moduleID[i] ) )
                                continue;
                            RadTreeNode nd = RadTree1.FindNodeByValue(moduleID[i]);
                            if (nd != null)
                            {
                                if (WebControlsTraceSwitch.Sw.TraceVerbose)
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadTreeComboModules ModuleComboTemplate RadTree1_DataBinding Removing PageID: {0}", moduleID[i]), WebControlsTraceSwitch.Sw.Info);
                                nd.Owner.Nodes.Remove(nd);
                            }
                        }
                    }
                    // Remove empty admin (never reached)
                    if ( IncludeAdmin && ndAdmin.Nodes.Count == 0 )
                        RadTree1.Nodes.Remove(ndAdmin);

                    if (WebControlsTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine("[V]RadTreeComboModules ModuleComboTemplate RadTree1_DataBinding Ok", WebControlsTraceSwitch.Sw.Info);
                }
                catch (Exception ex)
                {
                    if (PageTraceSwitch.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"RadTreeComboModules ModuleComboTemplate RadTree1_DataBinding ex : {0}", ex),PageTraceSwitch.Sw.Info);
                    throw;
                }
                finally
                {
                    if (drCurrentModuleDefinitions != null)
                        drCurrentModuleDefinitions.Close();
                }
            }
        }

        /// <summary>
        /// Represents a combobox filled with a hierachical treeview of portal pages
        /// </summary>
        public RadTreeComboModules()
        {
        }

        protected override void InitItemTemplate()
        {
            ItemTemplate = new ModuleComboTemplate(PortalID, TreeViewSkin);
        }

        protected override string[] UnSelectable
        {
            get
            {
                if ( string.IsNullOrEmpty(UnSelectables) )
                    return new string[] { "0", "1" };
                string[] tb = UnSelectables.Split(new char[]{';'},StringSplitOptions.RemoveEmptyEntries);
                string[] tb2  =   new string[tb.Length+2];
                tb2[0]  =   "0";
                tb2[1]  =   "1";
                for (int i=0; i < tb.Length ; i++)
                    tb2[i+2]    =   tb[i];
                return tb2;
            }
        }

        public override string SelectedTreeViewValue
        {
            get
            {
                if (ItemTemplate != null)
                {
                    return ((ModuleComboTemplate)ItemTemplate).selVal;
                }
                return null;
            }
            set
            {
                if (ItemTemplate != null)
                {
                    ((ModuleComboTemplate)ItemTemplate).selVal = value;
                    if (WebControlsTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadTreeComboModules SelectedTreeViewValue SET value: {0}", value), WebControlsTraceSwitch.Sw.Info);
                }
            }
        }
    }
}
